package com.mars.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mars.security.core.properties.LoginType;
import com.mars.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义成功的处理请求后的方法:
 * 1、实现 AuthenticationSuccessHandler ，重写其onAuthenticationSuccess()方法
 * 2、当构建通用方法时，需要继承SpringSecurity默认处理器 SavedRequestAwareAuthenticationSuccessHandler
 * @author MARS
 * @date 2018/7/23
 */
@Component("myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 处理成功登录后的结果
     * @param request
     * @param response
     * @param authentication 包装了 用户的信息
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response
            , Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功,YEYE");

        // 判断是否是请求还是登录页
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        } else {
            // 调用父类方法进行跳转
            super.onAuthenticationSuccess(request,response,authentication);
        }
    }
}
